package types

import (
	"cloud-entropy-storage-system/volume/internal/svc"
	"github.com/asdine/storm/v3"
	"sync"
)

type StormIndex struct {
	db   *storm.DB
	lock sync.Mutex
}

func NewIndex(db *storm.DB) *StormIndex {
	index := new(StormIndex)
	index.db = db
	return index
}

func (n *StormIndex) List() (resp []svc.FileInfo, err error) {
	// todo
	return
}

func (n *StormIndex) Has(fid uint64) bool {
	f := new(svc.FileInfo)
	err := n.db.One("Fid", fid, &f)
	if err != nil {
		if err == storm.ErrNotFound {
			return false
		}
		return false
	}
	return true
}

func (n *StormIndex) Get(fid uint64) (*svc.FileInfo, error) {
	var f svc.FileInfo
	err := n.db.One("Fid", fid, &f)
	if err != nil {
		if err == storm.ErrNotFound {
			return nil, nil
		}
		return nil, err
	}
	return &f, nil
}

func (n *StormIndex) Set(fi *svc.FileInfo) error {
	n.lock.Lock()
	defer n.lock.Unlock()
	return n.db.Save(fi)
}

func (n *StormIndex) Delete(id int) error {
	n.lock.Lock()
	defer n.lock.Unlock()
	return n.db.UpdateField(&svc.FileInfo{ID: id}, "Flag", svc.FlagDelete)
}

func (n *StormIndex) Close() error {
	return n.db.Close()
}
